//
//  WDInAppPurchaseManager.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/6/15.
//
#import "WDGroMoreHeader.h"
#import "WDBMS.h"
#import "WDInAppPurchaseManager.h"
//#import "WDCallBack.h"
//#import "WDJsonManager.h"
#import "WDAdStatusManager.h"
#import "WDInAppPurchaseHandleManager.h"
//#import "WDHeader.h"
//沙盒测试环境验证
#define SANDBOX @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式环境验证
#define AppStore @"https://buy.itunes.apple.com/verifyReceipt"
@implementation WDInAppPurchaseManager
{
    NSInteger verifyCount;
    BOOL isGetList;
    int _isResume;//是否恢复的购买
    NSString *_productId;//内购中的产品ID
}

static WDInAppPurchaseManager *_InAppPurchaseManager = nil;
+ (instancetype)shareInAppPurchaseManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _InAppPurchaseManager = [[self alloc] init];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:_InAppPurchaseManager];
    });
    return _InAppPurchaseManager;
}

- (void)launchInAppPurchase:(NSString *)productId
{
    if ([WDGroMorePublic manager].onBeginInAppPurchaseCallBack) {
        [WDGroMorePublic manager].onBeginInAppPurchaseCallBack(productId);
    }
    _isResume = 0;
    _productId = productId;
    if([SKPaymentQueue canMakePayments]){
        [self requestProductData:productId];
    }else{
        WDLog(@"不允许程序内付费");
        if ([WDGroMorePublic manager].onInAppPurchaseCallBack) {
            [WDGroMorePublic manager].onInAppPurchaseCallBack(NO, @"不允许程序内付费", productId);
        }
    }
}

- (void)restoreInAppPurchase:(NSString *)productId
{
    if ([WDGroMorePublic manager].onBeginRestoreInAppPurchaseCallBack) {
        [WDGroMorePublic manager].onBeginRestoreInAppPurchaseCallBack(productId);
    }
    _isResume=1;
    _productId = productId;
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

#pragma mark -- 恢复交易处理   恢复失败
-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{
    NSLog(@"-------paymentQueue----");
    if ([WDGroMorePublic manager].onRestoreInAppPurchaseCallBack) {
        [WDGroMorePublic manager].onRestoreInAppPurchaseCallBack(NO, error.localizedDescription, _productId);
    }
    dispatch_async(dispatch_get_main_queue(), ^{
//        if ([SVProgressHUD isVisible]) {
//            [SVProgressHUD dismiss];
//        }
    });

}

- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
    
    if ([WDGroMorePublic manager].onRestoreInAppPurchaseCallBack) {
        [WDGroMorePublic manager].onRestoreInAppPurchaseCallBack(YES, @"", _productId);
    }
}

-(void)removeObserver
{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)requestProductLists:(NSArray *)array
{
    isGetList = YES;
    NSSet *nsset = [NSSet setWithArray:array];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
}

- (void)requestProductData:(NSString *)type{
    WDLog(@"-------------请求对应的产品信息----------------");
    [[WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager] billing_purchase_request:_productId];
    isGetList = NO;
    NSArray *product = [[NSArray alloc] initWithObjects:type, nil];
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    verifyCount = 0;
    WDLog(@"--------------收到产品反馈消息---------------------");
    NSArray *product = response.products;
    if([product count] == 0){
        WDLog(@"--------------没有商品------------------");
        if ([WDGroMorePublic manager].onInAppPurchaseCallBack) {
            [WDGroMorePublic manager].onInAppPurchaseCallBack(NO, @"没有商品", @"");
        }
        return;
    }
    WDLog(@"productID:%@", response.invalidProductIdentifiers);
    SKProduct *p = nil;
    NSMutableArray *array = [NSMutableArray array];
    for (SKProduct *pro in product) {
        WDLog(@"%@", [pro description]);
        WDLog(@"%@", [pro localizedTitle]);
        WDLog(@"%@", [pro localizedDescription]);
        WDLog(@"%@", [pro price]);
        WDLog(@"%@", [pro productIdentifier]);
        WDLog(@"%@", pro.priceLocale.currencyCode);
        
        [array addObject:pro];
        if([pro.productIdentifier isEqualToString:_productId]){
            p = pro;
        }
    }
    if (isGetList)
    {
        [WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager].productIds = [NSArray arrayWithArray:array];
//        if ([WDGroMorePublic manager].onProductListCallBack)
//        {
//            [WDGroMorePublic manager].onProductListCallBack(array);
//        }
    }
    else
    {
        
        SKPayment *payment = [SKPayment paymentWithProduct:p];
        WDLog(@"发送购买请求");
        [[SKPaymentQueue defaultQueue] addPayment:payment];
        // 可以把我们的自己订单和IAP的交易订单绑定,本地存储订单信息
    }
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    WDLog(@"------------------错误-----------------:%@", error);
}
- (void)requestDidFinish:(SKRequest *)request{
    WDLog(@"------------反馈信息结束-----------------");
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{
//    NSString *resultA=@"";
    SKPaymentTransaction *tran = [transaction lastObject];
    switch (tran.transactionState) {
        case SKPaymentTransactionStatePurchased:
            [[WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager] billing_Revenue:tran];
            WDLog(@"交易完成");
            if (_isResume==0) {
                [self verify:tran appleUrl:AppStore];
//                NSData *receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
//                resultA=[self encode:receiptData.bytes length:receiptData.length];
//                WDLog(@"购买结果票据：%@",resultA);
                // 收据发送到服务器
                // 收据验证成功之后结束交易
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                 // 删除保存的订单信息
            }
            else
            {
//                [self verify:tran appleUrl:AppStore];
//                NSString *resultB=[self encode:tran.transactionReceipt.bytes length:tran.transactionReceipt.length];
                WDLog(@"恢复结果票据");
                // 收据发送到服务器
                // 收据验证成功之后结束交易
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
            
            break;
        case SKPaymentTransactionStatePurchasing:
            WDLog(@"商品添加进列表");
            [[WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager] billing_purchase_success:tran];
            break;
        case SKPaymentTransactionStateRestored:
            WDLog(@"已经购买过商品");
            [self verify:tran appleUrl:AppStore];
            [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            break;
        case SKPaymentTransactionStateFailed:
            WDLog(@"交易失败");
            WDLog(@"%ld",tran.error.code);
            [self errorReason:tran];
            [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            
            break;
        default:
            break;
    }
}
- (void)errorReason:(SKPaymentTransaction *)tran{
    NSError *error = tran.error;
    NSString *detail;
    if (error != nil) {
        switch (error.code) {
            case SKErrorUnknown:
                WDLog(@"SKErrorUnknown");
                detail = @"未知的错误，您可能正在使用越狱手机";
                break;
            case SKErrorClientInvalid:
                WDLog(@"SKErrorClientInvalid");
                detail = @"当前苹果账户无法购买商品(如有疑问，可以询问苹果客服)";
                break;
            case SKErrorPaymentCancelled:
                WDLog(@"SKErrorPaymentCancelled");
                detail = @"订单已取消";
                break;
            case SKErrorPaymentInvalid:
                WDLog(@"SKErrorPaymentInvalid");
                detail = @"订单无效(如有疑问，可以询问苹果客服)";
                break;
            case SKErrorPaymentNotAllowed:
                WDLog(@"SKErrorPaymentNotAllowed");
                detail = @"当前苹果设备无法购买商品(如有疑问，可以询问苹果客服)";
                break;
            case SKErrorStoreProductNotAvailable:
                WDLog(@"SKErrorStoreProductNotAvailable");
                detail = @"当前商品不可用";
                break;
            default:
                WDLog(@"No Match Found for error");
                detail = @"未知错误";
                break;
        }
    }

    [[WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager] billing_purchase_failed:tran errorMsg:detail];
    if ([WDGroMorePublic manager].onInAppPurchaseCallBack) {
        [WDGroMorePublic manager].onInAppPurchaseCallBack(NO, detail, @"");
    }
}


- (void)verify:(SKPaymentTransaction *)transaction appleUrl:(NSString *)appleUrl {
    WDLog(@"verify");
    verifyCount++;
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接请求数据
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    //创建请求到苹果官方进行购买验证
    NSURL *url=[NSURL URLWithString:appleUrl]; // 正式上架用 AppStore
    NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
    requestM.HTTPBody=bodyData;
    requestM.HTTPMethod=@"POST";
    //创建连接并发送同步请求
    WDLog(@"创建连接并发送同步请求");
    NSError *error=nil;
    NSData *responseData=[NSURLConnection sendSynchronousRequest:requestM returningResponse:nil error:&error];
    
    if (error) {
        WDLog(@"---验证购买过程中发生错误，错误信息---：%@",error.localizedDescription);
        [[WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager] billing_Revenue_Record:transaction isSuccess:NO errorMsg:error.localizedDescription orderId:@""];
        return;
    }
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
    WDLog(@"-------验证成功后返回的的json--------%@",dic);
    NSString *environment = [dic objectForKey:@"environment"];
    WDLog(@"----environment:%@",environment);
    if([dic[@"status"] intValue] == 0){
        verifyCount = 0;
        WDLog(@"购买成功-------");
        NSDictionary *dicReceipt= dic[@"receipt"];
        
        NSMutableArray *temparray = [NSMutableArray array];
        NSArray *inapps = dicReceipt[@"in_app"];
        [temparray addObjectsFromArray:inapps];
        for (int i = 0; i < temparray.count-1; i++) {
            
            for (int j = 0; j < temparray.count-1; j++) {
                NSDictionary *dict = temparray[j];
                NSDictionary *dict1 = temparray[j+1];
                
                NSInteger a = [[dict objectForKey:@"original_purchase_date_ms"] integerValue];
                NSInteger b = [[dict1 objectForKey:@"original_purchase_date_ms"] integerValue];
                if (a < b)
                {
                    NSDictionary *dict2 = temparray[j];
                    temparray[j] =  temparray[j+1];
                    temparray[j+1] = dict2;
                }
            }
        }
        
        
        for (NSDictionary *dicInApp in temparray) {
            
            NSString *transaction_id = dicInApp[@"transaction_id"];

            NSString *productIdentifier= dicInApp[@"product_id"];//读取产品标识
            
            NSString * proType = [self productType:productIdentifier];
            
            [WDGroMoreTrackManager track:BMS_EVENT_PURCHASE_SUCCESS params:@{BMS_PARAM_WDS:BMS_WDS_IAP_SUCCESS,BMS_PARAM_PDI:productIdentifier,BMS_PARAM_AD_TYPE:proType,BMS_PARAM_PDN:productIdentifier,BMS_PARAM_ODN:transaction_id} dType:BMS_DTYPE_PURCHASE desc:BMS_WDS_IAP_SUCCESS options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];

            if([proType isEqualToString:@"2"]){//订阅
                
                WDLog(@"-2---%@",productIdentifier);
          
                if (![[NSUserDefaults standardUserDefaults] objectForKey:productIdentifier]) {
                    
                    WDLog(@"---productIdentifier:%@",productIdentifier);
                    [self saveInformation:productIdentifier];
                    [self completeTransaction:transaction productId:productIdentifier transaction_id:transaction_id dict:dicInApp]; //代理方法 不知道会不会走 如果不走也可以把verify放这里
                    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:productIdentifier];

                }
            }else {//消耗性

                WDLog(@"-1--%@-",productIdentifier);

                NSString *transaction_id = dicInApp[@"transaction_id"];
                WDLog(@"---productIdentifier:%@",productIdentifier);
                [self saveInformation:productIdentifier];
                [self completeTransaction:transaction productId:productIdentifier transaction_id:transaction_id dict:dicInApp]; //代理方法 不知道会不会走 如果不走也可以把verify放这里
            }
   
        }
        
        
//        NSDictionary *dicInApp=[temparray firstObject];
//        NSString *productIdentifier= dicInApp[@"product_id"];//读取产品标识
//        NSString *transaction_id = dicInApp[@"transaction_id"];
//        WDLog(@"---dicInApp:%@",dicInApp);
//        WDLog(@"---productIdentifier:%@",productIdentifier);
//        [self saveInformation:productIdentifier];
//        [self completeTransaction:transaction productId:productIdentifier transaction_id:transaction_id dict:dicInApp]; //代理方法 不知道会不会走 如果不走也可以把verify放这里
    }else{
        //验证失败，可能是非法手段，数量没有 +1
        WDLog(@"购买失败，未通过验证！");
        if (verifyCount <= 5)
        {
            [self verify:transaction appleUrl:SANDBOX];
        }
        else{
            verifyCount = 0;
            [self failedTransaction:transaction];
        }
        
//        [self failedTransaction:transaction];
//        [self completeTransaction:transaction productId:@""];
    }

}
// 验证成功后 说明该用户正常交易，保存信息，并且可以给用户金币啦。这边我用的NSUserDefaults保存，这样会导致用户换手机或者卸载重新下载之后信息丢失，如果不希望这样，可以和用户的账户绑定后保存到公司的服务器里面。
- (void)saveInformation:(NSString *)proId {

//    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
//    if ([proId isEqualToString:self.currentProId]) {
//        NSInteger purchasedCount=[defaults integerForKey:proId];//已购买数量
//        [[NSUserDefaults standardUserDefaults] setInteger:(purchasedCount+1) forKey:proId];
//    }else{
//        [defaults setBool:YES forKey:proId];
//    }
    //在此处对购买记录进行存储，可以存储到公司的服务器端 这里用的 UserDefaults

    //       WDLog(@"====数量===%@",  [[NSUserDefaults standardUserDefaults] objectForKey:productIdentifier]);
    //       这里可以让用户的金币+1 并保存用户金币数量

    //验证成功 结束交易

}

//正常交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction productId:productId transaction_id:(NSString *)transaction_id dict:(NSDictionary *)dict{
    WDLog(@"-------交易结束---%@----%@",transaction_id,dict);
    
    
    
    [[WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager] billing_Revenue_Record:transaction isSuccess:YES errorMsg:@"" orderId:transaction_id];
    if ([WDGroMorePublic manager].onInAppPurchaseCallBack) {
//        [[WDGroMoreBmsReportManager manager] purchaseBmsEventWithProductId:productId andPamt:[WDGroMoreJosnManager renvenueWithProductId:productId] andOrderNumber:transaction_id];
        [WDGroMorePublic manager].onInAppPurchaseCallBack(YES, @"",productId);
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

//交易失败
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    NSString *msg;
    if(transaction.error.code == SKErrorPaymentCancelled) {
        WDLog(@"用户取消交易");
        msg = @"用户取消交易";
    } else {
        WDLog(@"交易失败");
        msg = @"交易失败";
    }
    if ([WDGroMorePublic manager].onInAppPurchaseCallBack) {
        [WDGroMorePublic manager].onInAppPurchaseCallBack(NO, msg, @"");
    }
    [[WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager] billing_Revenue_Record:transaction isSuccess:NO errorMsg:msg orderId:@""];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    // 都要有结束交易的方法
}

- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    // 对于已购商品，这里处理恢复购买的逻辑

    // ********

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}


- (NSString *)encode:(const uint8_t *)input length:(NSInteger)length {
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t *output = (uint8_t *)data.mutableBytes;
    for (NSInteger i = 0; i < length; i += 3) {
        NSInteger value = 0;
        for (NSInteger j = i; j < (i + 3); j++) {
            value <<= 8;
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        NSInteger index = (i / 3) * 4;
        output[index + 0] =                    table[(value >> 18) & 0x3F];
        output[index + 1] =                    table[(value >> 12) & 0x3F];
        output[index + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[index + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }
    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}


- (NSString *)productType:(NSString *)productId
{
    NSString *type = @"0";
    if ([[WDGroMoreJosnManager consumableProductIdForSDKConfigFile] containsObject:productId])
    {
        type = @"1";
    }
    if ([[WDGroMoreJosnManager nonConsumableProductIdForSDKConfigFile] containsObject:productId] || [[WDGroMoreJosnManager subscribeProductIdForSDKConfigFile] containsObject:productId])
    {
        type = @"2";
    }
    return type;
}

@end
